package com.tf_cut.backend.util;

import com.tf_cut.backend.agent.service.AgentCashOrderService;
import com.tf_cut.backend.mapper.SellerAccountMapper;
import com.tf_cut.backend.seller.service.SellerProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class SerialNoUtil {
    @Resource
    private SellerAccountMapper sellerAccountMapper;
    @Autowired
    private AgentCashOrderService agentCashOrderService;
    @Autowired
    private SellerProjectService sellerProjectService;

    /**
     * 根据类别、平台生成流水号
     * 格式为 类别+平台+日期+顺序号(共19位)
     * @param type
     * @param platform
     * @return
     */
    public String genSerialNo(String type, String platform, String merchant){
        if(merchant.length()==1){
            merchant="0000"+merchant;
        }else if(merchant.length()==2){
            merchant="000"+merchant;
        }else if(merchant.length()==3){
            merchant="00"+merchant;
        }else if(merchant.length()==4){
            merchant="0"+merchant;
        }
        //设置默认渠道
        if(platform == null){
            platform = "A";
        }
        String rules = type + platform + merchant + getCurrentDate();
        String lastOrder=null;
        if(type.equals("T")){
            lastOrder=agentCashOrderService.qryLastSerial(rules+"%");
        }else if(type.equals("X")){
            lastOrder = sellerProjectService.qryLastSerial(rules + "%");
        }else if(type.equals("F")){
        	lastOrder = sellerAccountMapper.qryLastOrderIdInF(rules + "%");
        }else if(type.equals("C")){
        	lastOrder = sellerAccountMapper.qryLastOrderIdInC(rules + "%");
        }else if(type.equals("Q")) {
            lastOrder = sellerAccountMapper.qryLastOrderIdInQ(rules + "%");
        }
        else {
            lastOrder = sellerAccountMapper.qryLastSerial(rules + "%");
        }
        //LA00001202010270001
        String serialNo = "";
        String before = "";
        String _serial = "";


        if(lastOrder != null && !lastOrder.equals("")) {
            String temp = lastOrder.substring(14,15);
            //如果数据库中该商户当日已经存在订单，计算新的订单号
            if (temp.equals("0")) {
                //如果最后一位是0则往前多截取一位
                _serial = lastOrder.substring(13);
                before = lastOrder.substring(0, 13);
            } else {
                //截取天数最后一位
                _serial = lastOrder.substring(14);
                before = lastOrder.substring(0, 14);
            }

            int serial = Integer.parseInt(_serial) + 1;

            serialNo = before + serial;
        }else{
            //如果数据库中不存在，直接以0001开始
            serialNo = rules + "0001";
        }

        return serialNo;
    }

    public String getCurrentDate(){
        return new SimpleDateFormat("yyyyMMdd").format(new Date());
    }


}
